<template>
  <div class="container">
    <el-form label-position="left" ref="elForm" class="ml-3" :model="form" :rules="rules" size="medium" label-width="100px">
      <el-form-item label="地址类型">
        <select v-model="form.addressType" placeholder="">
          <option label="静态" value='static'></option>
          <option label="动态" value='dhcp'></option>
        </select>
      </el-form-item>
      <el-form-item label="设备IPv4地址">
        <input :disabled="form.addressType === 'dhcp'" class="w-[202px]" v-model="form.ipAddress" type="text" >
      </el-form-item>
      <el-form-item label="IPv4子网掩码">
        <input :disabled="form.addressType === 'dhcp'" class="w-[202px]" v-model="form.subnetMask" type="text" >
      </el-form-item>
      <el-form-item label="IPv4默认网关">
        <input :disabled="form.addressType === 'dhcp'" class="w-[202px]" v-model="form.defaultGateway" type="text" >
      </el-form-item>
      <el-form-item label="物理地址">
        <input disabled class="w-[202px]" v-model="form.macAddress" type="text" >
      </el-form-item>
      <el-form-item label="首选DNS服务器">
        <input :disabled="form.addressType === 'dhcp'" class="w-[202px]" v-model="form.primaryDNS" type="text" >
      </el-form-item>
      <el-form-item label="备用DNS服务器">
        <input :disabled="form.addressType === 'dhcp'" class="w-[202px]" v-model="form.secondaryDNS" type="text" >
      </el-form-item>
        <el-button class="!mt-8" type="primary" @click="save()" style="width: 120px; margin-left: 0px">保存</el-button>
    </el-form>
  </div>
</template>

<script>
import {getNetconfig, getPortsconfig, postNetconfig} from "../../../api/api";

export default {
  name: 'index',
  data() {
    return {
      title: "",
      open: false,
      httpPort: 80,
      originalIpAddress: '', // 用于存储原始IP地址
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
      },
      rules: {
      },
    }
  },
  created() {
    getNetconfig().then(res =>{
      this.form = res.data;
      this.originalIpAddress = res.data.ipAddress;
    })
    getPortsconfig().then(res =>{
      this.httpPort = res.data.httpPort;
    })
  },
  methods: {
    /**
     * 检查字符串是否为有效的IPv4地址
     * @param {string} ip - 要验证的IP地址字符串
     * @returns {boolean} - 如果有效则返回 true, 否则返回 false
     */
    isValidIp(ip) {
      if (!ip || typeof ip !== 'string') {
        return false;
      }
      const ipRegex = /^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
      return ipRegex.test(ip);
    },

    // --- 修改后的 save 方法 ---
    save(){
      // 仅当地址类型为 "静态" 时才进行验证
      // 1. 验证设备IPv4地址
      if (!this.isValidIp(this.form.ipAddress)) {
        this.$message.error('设备IPv4地址格式不正确或为空');
        return; // 验证失败，中止执行
      }

      // 2. 验证IPv4子网掩码
      if (!this.isValidIp(this.form.subnetMask)) {
        this.$message.error('IPv4子网掩码格式不正确或为空');
        return;
      }

      // 3. 验证IPv4默认网关
      if (!this.isValidIp(this.form.defaultGateway)) {
        this.$message.error('IPv4默认网关格式不正确或为空');
        return;
      }

      // 4. 验证首选DNS服务器
      if (!this.isValidIp(this.form.primaryDNS)) {
        this.$message.error('首选DNS服务器格式不正确或为空');
        return;
      }

      // 5. 验证备用DNS服务器（此项为可选，如果填写了，就必须是正确的IP格式）
      if (this.form.secondaryDNS && !this.isValidIp(this.form.secondaryDNS)) {
        this.$message.error('备用DNS服务器格式不正确');
        return;
      }
      const ipHasChanged = this.form.addressType === 'static' && this.originalIpAddress !== this.form.ipAddress;

      if (ipHasChanged) {
        // 如果IP地址变更，执行“发送后不等返回，直接提示跳转”的逻辑
        this.$confirm('设备IP将变更。点击“确定”将修改IP并跳转到新地址。', '重要提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          postNetconfig(this.form);
          setTimeout(() => {
            window.location.href = `http://${this.form.ipAddress}:${this.httpPort}`;
          }, 1000); // 延迟1000毫秒 (1秒)
        }).catch(() => {
        });

      } else {
        // 如果IP地址未变更（或为DHCP模式），则执行标准保存流程
        postNetconfig(this.form).then(res => {
          this.$message({
            message: '保存成功',
            type: 'success'
          });
          // 成功后可以更新一下原始IP，以防用户连续点击保存
          this.originalIpAddress = this.form.ipAddress;
        }).catch(err => {
          this.$message.error('保存失败');
        });
      }
    }
  },
  computed: {
    enableValue: {
      get() {
        return String(this.form.enable);  // Convert to string for comparison
      },
      set(value) {
        this.form.enable = Number(value); // Convert back to number for data
      }
    }
  },
}
</script>

<style scoped>
.container {
}
.button {
  margin-top: 5%;
}
select {
  width: 202px;
}
</style>
